//@author A0096466N
//
// **********
//
// takes the most recent past
// from history and undoes it
//
// **********

#include "Undo.h"

Undo::Undo(void) {

}

Undo::~Undo(void) {

}

string Undo::execute(History & history,vector<Task> & forUIDisplay, vector<Task> & store) {
	
	ofstream writeFile;
	writeFile.open(FILENAME_LOGGER.c_str(), ofstream::out | ofstream::app);
	writeFile << "Attempting to undo" << endl;
	writeFile.close();

	if(history.getPastSize() == NIL) {
		throw exception("Nothing to undo");
	}

	Event undo = history.getPast();
	Task lastAction = undo.getTask();
	string command = undo.getCommand();
	string dummy;
	assert(command != EMPTY);
	
	if(command == ADD) {
	
		Delete del;
		dummy = del.execute(lastAction,forUIDisplay,store);
		history.transferToFuture();
		return "undone add";

	} else if(command == DELETE_) {
		Add add;
		dummy = add.execute(lastAction,store);
		Searcher search;
		forUIDisplay = search.execute(lastAction.getTaskName(),store);
		history.transferToFuture();
		return "undone delete";

	} else if(command == MODIFY) {
		history.transferToFuture();

		Task modTask;
		modTask.changeTaskName(lastAction.getModifiedTaskName());
		modTask.changeDeadline(lastAction.getModifiedDeadline());
		modTask.changePriority(lastAction.getModifiedPriority());
		modTask.changeTime(lastAction.getModifiedTime());
		modTask.changeDateInSeconds(lastAction.getModifiedDateInSeconds());

		modTask.changeModifiedTaskName(lastAction.getTaskName());
		modTask.changeModifiedDeadline(lastAction.getDeadline());
		modTask.changeModifiedPriority(lastAction.getPriority());
		modTask.changeModifiedTime(lastAction.getTime());
		modTask.changeModifiedDateInSeconds(lastAction.getDateInSeconds());

		Modify modify;
		modify.execute(modTask,forUIDisplay,store);
		return "undone modify";

	} else if(command == RESET) {
		store = history.getPastStore();
		forUIDisplay = store;
		
		string data;
		Parser parse;
		Storage storage;
		vector<string> forTxtRewrite;
		for(vector<Task>::iterator iter = store.begin(); iter != store.end(); iter++) {
			data = parse.convertToString(*iter);
			forTxtRewrite.push_back(data);
		}
		storage.rewrite(forTxtRewrite);
		
		history.transferToFuture();
		return "undone reset";
	
	} else if(command == MARK) {
		history.transferToFuture();
		Task modTask;
		modTask.changeTaskName(lastAction.getTaskName());
		modTask.changeStatus(lastAction.getModifiedStatus());
		modTask.changeModifiedStatus(lastAction.getStatus());
		
		Mark mark;
		mark.execute(modTask,forUIDisplay,store);

		return "undone mark";
	
	} else {
		throw exception("undo error");
	}
}